Repository navigation
Conversation
…cs context after validation
`{A} {B}` used to parse, then search planned only `{A}` while metrics
ANDed both selectors. Juxtaposed operands are now a parse error; a
trailing operator with no operand after it is still accepted.
…ed query IR Add traceql_ir: a Query (pipeline of spanset expressions, metrics function, hints, second stage) lowered from the participle AST. Search, the complexity estimate, tags v2, values v2 and the metrics filter extraction consume it instead of walking Head/Tail. The search planner replays the linear-script chain planning over the IR operand list, so generated SQL and errors are unchanged.
…share planner entry points Structural operators bind tighter than && and ||, which share a level, all left-associative. Search planning flattens the tree back to its operand chain, so generated SQL is unchanged.
…s by spss Every selector now yields an uncapped (trace_id, span_id) set; the 100-span groupArray caps on operands, &&, || and the attribute-less planner are gone. One final search-spanset stage groups result spans by trace, lists the spss newest (default 3, the Tempo default) and reports the true matched count; the trace limit applies after it. /api/search reads spss and rejects non-positive values. Search, including the attribute-less trace pre-pick, selects spans that start in (from, to]; metrics keep [from, to). The nestedSetParent<0 root filter applies before the cap. On clusters, search reads the Distributed attribute and spans tables with GLOBAL IN/JOIN, so traces on every shard are found.
… image E2E_TESTS_REF names the suite branch e2e-deps checks out (traceql-structural-ops). E2E_CLICKHOUSE_IMAGE (default 25.3) and E2E_GIGAPIPE_IMAGE select the stack's images, E2E_TEST_ARGS passes jest arguments, and E2E_TESTS_DIR may be absolute. A second CI job runs the TraceQL grid suite on ClickHouse 24.9.
… spanset stage
The {} pre-pick keeps the traces with the newest in-range spans, ties by trace id, as the final stage does. Plan tests check date pruning across midnight.
{A} && {B} matches a trace when both sides return spans in it and returns
both sides' spans, deduplicated; {A} || {B} returns the deduplicated union.
Search plans the lowered spanset tree directly, so grouped operands and
mixed &&/|| chains follow Tempo precedence. Structural operators still
evaluate as &&.
Parse >, <, ~ and their ! and & variants between spansets (>, < and !~
stay comparisons inside a selector) and evaluate them per trace: operand
spans are keyed by span or parent id from the traces table, read by trace
with no time bound, and related in one windowed pass. Only spans whose
parent chain reaches a root take part; pointer jumping resolves that for
traces with a missing parent. Structural queries pin enable_analyzer=1
and fail on ClickHouse older than 24.9.
<<& and <<~ are parse errors naming &<< and !<<. {} is accepted as an
operand of a spanset operator and reads every span in range.
… and reject them in metrics Metrics queries with one-hop operators fail instead of flattening both selectors. Edges keep one parent per span.
…mping `>>`, `<<`, `!>>`, `!<<`, `&>>` and `&<<` parse and evaluate on the span tree: a WITH RECURSIVE pointer jump over every span of the candidate traces carries ancestor flags (up) and fan-in descendant marks (down), with root reachability from the same jump. No structural operator maps to && any more. The round limit R comes from GIGAPIPE_TRACEQL_ANCESTRY_ROUNDS (default 20) for both this jump and the one-hop reachability jump. A pointer still set after R rounds (a trace deeper than 2^R spans, or a parent cycle) fails the query with a message naming the setting. Search reads the whole result before responding so that the error reaches the client. The e2e stack sets R=3. Metrics rejects transitive operators like one-hop ones.
…on between structural planners
Every metrics function (range, instant, histogram, compare) reads the spans a search for the same expression returns, uncapped, so ||, && and structural operators are honoured instead of flattening every selector into one AND list. Spans count by start time in (from, to]; exemplars come from the result spans. Structural metrics queries need ClickHouse 24.9 and run with the analyzer, like search. Stages written after the last operand of a chain end the whole query.
…ning off the caller's context
…esult spans
Tags v2 and values v2 read the attributes of the spans a search for the query
returns, joined on (trace_id, span_id), so structural, && and || queries narrow
the suggestions. A query without a selector or a lone {} keeps the unfiltered
path. Values v2 strips tag scopes like values v1, and without a query lists
values instead of tag keys. Costly queries are read by complexity portions
and merged instead of falling back to every tag.
…vel aggregates A query is a pipeline of elements joined by |: spanset expressions and scalar filters (count, avg, min, max, sum compared with a number or duration), with parenthesised pipelines as operands. Each stage plans as one CTE; a scalar filter aggregates the deduplicated result spans of the whole preceding expression per trace, before the spss cap, and gates metrics and autocomplete the same way. Search returns the aggregate values as spanset attributes named by their canonical form. Invalid scalar filters fail at plan time with Tempo's texts.
…regate arguments as attributes
…d aggregate arguments Spanset filters and aggregate arguments parse Tempo's field-expression language with expr.y precedence: attribute-vs-attribute comparison, + - * / % ^, unary minus and !, parentheses and = nil / != nil. A boolean combination of attribute op literal keeps the bitset plan; any other filter pivots the attributes it reads to one row per span and evaluates the expression under the nil rule. Aggregate values read the same pivot. The bitset prefilter reads the rows of every key-reading term, so status, kind and root terms combine with attribute terms, and reads every row when the filter can hold without them, as for duration || attribute.
… and reject bare words that meet no field
… before
A spanset expression after another pipeline stage draws every operand from
that stage's spans, nested pipelines included, while ancestry and root
reachability still read the full trace tree. {A} | {B} is a span-level
intersection. A narrowed stage keeps the previous stage's spanset
attributes, and a lone parenthesised pipeline stage appends its own.
… qualified span-row columns
…typing and filtered autocomplete Align the two lists of differences from Tempo, scope the (from, to] rule to autocomplete with a query, and name every spanset operator autocomplete accepts.
rita7lopes
left a comment
There was a problem hiding this comment.
Four things before I approve, plus some docs changes. Line numbers are from that commit.
1. Don't let one bad trace fail the whole query
unresolvedGuard (structural.go:454, used at :314 and :342) throws if any trace still has an unresolved pointer after the last round. A client can cause that by sending a span that is its own parent, and I found no parent validation in the writer. Transitive queries then fail for as long as that trace is in range, and the error tells the operator to raise GIGAPIPE_TRACEQL_ANCESTRY_ROUNDS, which can't help with a cycle.
Please change this to:
- Skip the unresolved trace, treating its spans as unreachable, and return the rest of the results.
- Log a warning with the trace ID. Depth overflow and a cycle can't be told apart at this point, so the message should name both causes and the setting. How you get the trace ID out to the log is up to you.
- Update the plan tests (
structural_plan_test.go), add a grid case with a cycle, and updatedocs/traceql.md, which currently says the query fails. - Check the e2e stack, which sets the round limit to 3: a real trace deeper than that limit will now be skipped rather than raise an error.
2. Keep from fixed in complexity portions for trace-level queries
ComplexRequestProcessor moves ctx.From to the oldest returned trace start between portions (complex_request_processor.go:26 and :60). That was safe when each selector stood alone, but it isn't safe now that results are evaluated per trace.
Above COMPLEXITY_THRESHOLD, a trace in a later portion can have .a before the moved from and .b after it. Then {.a} >> {.b} and {.a} && {.b} lose the trace, {.a} !>> {.b} wrongly returns its .b span, and | count() > 2 undercounts, all with no error. The trace start also isn't bounded by the request, so from can move earlier than requested and return spans outside the range.
Portions already split by cityHash64(trace_id), so memory stays bounded without moving from. Please keep from fixed for anything other than a lone selector, and never let it go earlier than the requested from. Please also add a test that forces more than one portion.
3. Benchmark metrics against master
Every metrics query, including {} | rate(), now builds a set of span IDs and reads the traces table again (metrics.go:110-132). The PR already lists cost as something to benchmark, and I'd like numbers before approving because this path carries existing dashboards, not just new syntax.
Please compare master and this branch on the same data over 24h, for {} | rate(), {...} | rate() by (...) and quantile_over_time(duration, 0.95), and post time and peak memory here. I'm not asking for a redesign up front. An out-of-memory failure or a slowdown of around 2x or more would block this, and otherwise we can merge.
4. Rebase and get CI green
There's one conflict, in the imports of reader/service/tempo.go: keep jx. Master has dropped the dead telemetry action from the k6 workflow and changed the cluster workflow, so k6 and the cluster build job should now run instead of failing during setup. Those are the runs I want to see pass.
Docs
- Please remove
docs/release-notes.mdand its README link. Upgrade notes belong in the GitHub release, so keep the breaking changes in this PR's description and we'll use them from there. Make the&&/||precedence change prominent, since it changes results silently. - Please cut
docs/traceql.mddown to what's specific to Gigapipe: requirements, time range, depth limit and skipped traces,spss, and differences from Tempo. Drop the sections that re-explain the language, link to Tempo's docs instead, and keep the#requirementsanchor thatconfiguration.mdlinks to. - Please add a comment to
reader/plugins/traces_planners.gosaying the new read paths (all_spans.go,field_filter.go,traceTreeedges,selectAttrs) don't callInitIndexPlannerPluginorAttrlessConditionPlannerPlugin, so nobody relies on them to scope rows. Nobody uses these hooks today, so no code changes there.
Accepted, no change needed
spss default of 3, the (from, to] range, &&/|| precedence, status = "error" as a type error, and the stricter-than-Tempo rejections are all fine.
Follow-ups, not blocking this PR
{nestedSetParent < 0} >> {.a = 1}returns nothing, because the root filter applies to the whole expression (pipeline.go:184). #1035 removes this code, so please list it as a known issue rather than fix it here. If #1035 is delayed, let's make it a clear error instead..95doesn't parse (lexer_rules v2.go:64). This needs a small separate PR with a test.- Complexity portioning is worth a separate look: a hard-coded threshold silently changes how a query runs, and #1034 extends it to autocomplete. The benchmark should help us decide whether trace-level queries still need it.
I'll review #1035 once this one is settled.
…ctural-ops Conflicts: - reader/service/tempo.go: imports keep jx and drop logql_transpiler/shared. - reader/service/tempo_metrics.go, reader/tempo/metrics_query.go: PR side, which replaces the metrics query builder #1040 patched. - reader/traceql/traceql_parser/model_v2.go: PR side guards. LogQL plan pins in testdata/sql_plans.json are re-recorded. The PR's SETTINGS renderer changes whitespace only: rendered SQL matches master once whitespace is stripped. Master's tests metrics_query_distributed_test.go and TestStringDanglingAndOr are carried unedited and do not pass against the PR side; the follow-up commit replaces them.
…anglingAndOr Replaces master's TestStringDanglingAndOr from #1057. The parser on this branch rejects a dangling && or ||, so the same inputs assert a parse error instead of a String() that does not panic.
…riant Replaces master's TestMetricsAttrJoinsAreGlobalOnCluster and TestMetricsJoinsAreLocalOnSingleNode from reader/tempo/metrics_query_distributed_test.go. TestMetricsPlannersHaveNoPlainDistributedJoin renders the range, instant, histogram, histogram exemplars, generic exemplars and compare planners with IsCluster and finds no plain join off a Distributed table, the shape behind ClickHouse error 288. It checks shape, not pinned SQL. TestMetricsPlannersHaveNoGlobalOnSingleNode keeps the single-node intent: the same planners use no GLOBAL without a cluster.
Add shared/chtest and the searchStore/seedStructural harness with one smoke case, on single node and two shards. The behaviour tests skip without GIGAPIPE_TEST_CLICKHOUSE.
Each portion read from the oldest trace start of the previous portion when that portion filled the limit. A later portion could then drop a trace whose earlier spans fell outside its range, or return spans before the requested from. Every portion now keeps the requested from, for every query shape. The threshold is a field on the complexity evaluator, which computes the portion count for both processors, and ComplexRequestProcessor takes its per-portion read as a function.
A trace with a parent cycle or deeper than the round limit no longer fails the whole query. Under >>, !>> and the one-hop operators an unresolved row acts like an orphan: it never matches a positive or & operator and always matches a negation. Under <<, !<<, &>> and &<<, down marks spread during the rounds, before a span is known to be unresolved, so a row-level test would let an unresolved span make a resolved ancestor match. These operators read a per-trace flag from the same _jump reference and return nothing from that trace. The flag reaches the final condition rather than filtering _resolved, because _matched is a LEFT JOIN and a dropped row would read as unmatched under !<<. Remove UnresolvedAncestryError, unresolvedGuard, unresolvedAncestryMessage and their call sites, including the metrics service.
Operator content (requirements, one shard per trace, depth limit) goes in docs/configuration.md and query-writer content (time range, search results, known issues, differences from Tempo) goes in the README. docs/traceql.md, docs/release-notes.md and their README lines are removed, so the docs list matches master. Also adds comments stating which reads the planner hooks in reader/plugins/traces_planners.go replace, with no code change.
A request whose plan has a structural operator starts a probe once the response is sent, at most once a minute per process, on its own timeout. The probe reads the same chain, one statement per jump and per portion, and one warn line names the affected trace IDs and both possible causes. compare() probes its baseline window, the only side with a chain.
The probe's deadline made clickhouse-go add max_execution_time to its queries, which a readonly=1 user is refused with code 164. The limit is a cancellation timer, so the context has no deadline and the queries carry no setting.
Over HTTP the ping is a query, so its deadline became max_execution_time and a readonly=1 user was refused with code 164. The watchdog panics after repeated failures, which stopped the reader.
Master changed buildFilterCTE, which this branch removes; the removal stands, since its regex filters render through matchRe and fieldSQL with NewStringVal. The by-label half of the escaping fix merged cleanly. The escaping test moves to the current buildByPivotCTE signature, and its regex cases to matchRe.
Fixes #986, #987, #988. Fixes the
||error in #1033. The Drilldown query still needsselect()of the nested-set intrinsics, which #1035 adds.Note
Merge with "Squash and merge", using the message under Squash message. #1035, #1066, the follow-up PRs and the top PRs all collapse into this branch first as merge commits, so
mastergets the whole stack as one commit.Breaking changes
Important
&&and||inside{…}now share one precedence level and group left to right, as in Tempo. Results change silently.{ .a = 1 && .b = 2 || .c = 3 }used to mean.a = 1 && (.b = 2 || .c = 3). It now means(.a = 1 && .b = 2) || .c = 3.Saved queries that mix
&&and||without parentheses need parentheses to keep their old meaning.Results that change
These queries used to return wrong results and now return exact ones. Saved dashboards and alerts that use them will show different numbers.
&>>,!>>,~were evaluated as&&and ignored the span tree. They now evaluate parent, ancestor and sibling relations.&&between selectors matched only when one span satisfied both sides and both sides' newest timestamps were equal.{A} && {B}now matches a trace when both sides have spans in it, and returns the spans of both sides.||returns the spans of either side, each once. Chains of three or more operands no longer drop operands.||and structural operators. A metrics query now counts exactly the spans a search for the same expression returns.| count() > 2) applied only to the last selector. They now apply to all result spans of the expression before them.spssfor more. Operands are no longer capped at 100 spans, andmatchedreports the true count.(from, to]. Search and metrics used[from, to).metrics by (...)labels could attach values to the wrong label names. Labels now match their values.{ status = error && .a = 1 },{ duration > 1s || .a = 1 }) could miss matching spans. They now return every match.{ .a = .b }compares two attributes. Before,.bwas the string".b".({A} | count() > 1)returns thecount()spanset attribute.>>,!>>and the one-hop operators, and<<,!<<,&>>and&<<return no spans from such a trace. Search, metrics, autocomplete and| count()stages follow the same rule. See Depth limit.fromto the oldest returned trace start between portions, which could lose traces from{A} >> {B}and{A} && {B}, return spans from{A} !>> {B}wrongly, undercount| count(), and return spans from before the requestedfrom. Every portion now reads the requested range.Queries that now fail
<<&and<<~are parse errors that name Tempo's spelling (&<<,!<<).{A} {B}(no operator) and a trailing operator ({A} &&) are parse errors.status = "error"is a type error. Writestatus = error. The same applies tokind.TraceQL structural operators need ClickHouse 24.9 or newer.Upgrade notes
enable_analyzer=1. Other TraceQL queries are unaffected.GIGAPIPE_TRACEQL_ANCESTRY_ROUNDS(1 to 32, default 20). Traces up to2^Rspans deep resolve. Spans of deeper or cyclic traces are treated as unreachable, and a rate-limited warning names those traces. See Depth limit.warnline naming the trace IDs, both causes and the setting. A probe that finds nothing logs nothing. It has its own time limit and never delays the response.TracesDataPluginreceives rows oftrace_id,span_id(all listed span ids) andspansets(an array of group key, span ids,matchedand attributes), and must emit 16 columns: the 8 existing ones, thenspanset_span_ids,matched,attr_names,attr_types,attr_values,attr_texts(one element per spanset), andspan_attr_keysandspan_attr_vals(one element per listed span). Plugins don't receive theselect()fields, soselect()returns no values through a plugin.InitIndexPlannerPlugin's select must expose unqualifiedtrace_idandspan_idcolumns. Neither it norAttrlessConditionPlannerPluginscopes the structural read paths;reader/plugins/traces_planners.gosays which read paths they don't cover.(trace_id, span_id), even with no structural operator. A PR at the top of this stack reads metrics with no spanset operator, scalar filter orby()stage in one pass (perf(traceql): read the traces table once for metrics over one selector #1091), and lands with it, somasternever carries this path alone. Structural operators read their candidate traces' parent links with no time bound, so every daily partition in retention is looked up.>>and<<run every configured round.Where Gigapipe deliberately differs from Tempo is listed in the README.
Summary
TraceQL structural operators are evaluated on the span tree, together with the Tempo pipeline around them. Before this, every structural operator was rewritten to a span-level
&&.> >> < << ~with!and&).<<&and<<~are not Tempo tokens and are now parse errors.+ - * / % ^, unary-and!, and= nil.by()/coalesce();select(); and the hintswith(sample=f, exemplars=N).cityHash64(trace_id)and keepfromfixed for every query shape.enable_analyzer=1. Other queries are unaffected.docs/configuration.md(TraceQL requirements and depth limit) and the README's TraceQL section (time range, search results, known issues, differences from Tempo). No new docs file.Evidence
{.a = 1} >> {.b = 2}is a parse error (TraceQL: bare structural operators>,>>,<,<<are rejected #986).{.a} &>> {.b}returns the spans matching both filters, whether or not they are related.{.a = 1} && {.b = 2}matches only spans carrying both attributes.After: each returns the spans Tempo returns. This is checked by the gigapipe-tests grid suite against a JS oracle, over ten fixture shapes (chains, two roots, root-less traces, orphans, a time-range edge, parent cycles, …) and across search, metrics and autocomplete.
| count()).from: processor and plan tests force more than one portion and check that every portion reads the requested range.TestParseRejectsDanglingAndOron master's inputs.go test ./...passes. ClickHouse behaviour tests pass on single node and two shards, 24.9 and 25.3, native and HTTP, in UTC and two other reader zones.grid.traceqlon two shards with 24.9, both pass on this branch and on the full stack tip, with no request near the grid's client timeout.buildjob and k6 run on CI for the first time with this push.Merge Danger
Door: two-way. No schema change or migration.
Blast Radius: wide. See Breaking changes.
Other effects:
{}can be an operand of&&,||and structural operators.span.x,resource.x,.x), as Grafana sends them, and without a query lists the tag's values. Tag autocomplete accepts a lone{}. Autocomplete for costly queries stays filtered by the query instead of falling back to every tag.readonly=1reader runs the unresolved-trace probe and passes the HTTP health check: neither setsmax_execution_timefor such a user.Merge order:
E2E_TESTS_REFis pinned totraceql-structural-ops(metrico/gigapipe-tests#23)..95, literals, scaling, quantiles (feat(traceql): configurable, visible complexity portioning with Tempo's search range cap #1085, feat(traceql): parse leading-dot, trailing-dot and exponent float literals #1086, feat(traceql): parse Tempo durations and quoted attribute names #1087, feat(traceql): scale sampled metrics by 1/f #1088, feat(traceql): return one series per quantile from quantile_over_time lists #1089).main; then this branch re-pinsE2E_TESTS_REFtomain.#1028 also pins
E2E_TESTS_REF, so whichever merges second gets a one-line Makefile conflict.Known gaps
master, fixes them.{}metrics against master. With the one-pass PR,{} | rate()meets the review's bar, but several lone{}shapes (instantrate,count,by,avg,sumand quantile; rangeavg,sum, quantile, histogram,by) are still slower than on master. They are tracked as a follow-up to the one-pass PR.Open questions
by();(count() > 2) && {B};count() > 1+2);{-.a}.Squash message
For "Squash and merge" at landing, when the whole stack has collapsed into this branch. Title, then body. Its Breaking changes and Upgrade notes are this description's plus those of #1035, #1066, the follow-ups and the top PRs, so re-read each before landing.